import {useState, useEffect} from 'react';
import {connect, useDispatch} from "react-redux";
import moment from 'moment';
import {View, Text, ScrollView, RichText} from '@tarojs/components';
import Taro, {useDidShow, useLaunch} from '@tarojs/taro';
import {
    Loading,
    Checkbox,
    Overlay,
    Tag,
    NoticeBar,
    ConfigProvider,
    Picker,
    Dialog,
    Badge,
    Image,
    Divider
} from '@nutui/nutui-react-taro';
import {
    AtIcon,
    AtButton,
    AtModal,
    AtModalHeader,
    AtModalContent,
    AtModalAction,
    AtActionSheet,
    AtActionSheetItem,
    AtBadge
} from "taro-ui";
import getBaseUrl from "../../../service/baseUrl";
import './index.less';
import {wxLogin} from "../../../utils";

const base = getBaseUrl();

function Index(props) {
    const {
        dispatch,
        currentPile = {},
        currentGun = {},
        chargingOrderInfo = {},
        selectGunCode,
        loading,
        startLoading,
        countDownTime,
        showStartModal,
        orderStarting = false,
        errorMsg,
        allActivities = [],
        myCouponsByStation: myCoupons = [],
        balance,
        integral,
        pointList = []
    } = props;
    console.log('startLoading', props);
    const timeStampForChargingOrderCreate = Taro.getStorageSync('timeStampForChargingOrderCreate');
    const nowTimeStamp = new Date().getTime();
    const diffSecond = timeStampForChargingOrderCreate ? 90 - parseInt((nowTimeStamp - timeStampForChargingOrderCreate) / 1000) : 0;
    const {rateDetail = [], gunIndex} = currentGun;
    const action = useDispatch();
    const isLogin = Taro.getStorageSync("isLogin");
    const isScan = Taro.getStorageSync("isScan");
    // const [currentGun, setGun] = useState({})
    const [activityVisible, setActivityVisible] = useState(false)
    const [balanceModal, setBalanceModalOpen] = useState(false)
    const [isOpened, setOpen] = useState(!isLogin)
    const [socPickerVisible, setSocPickerVisible] = useState(false);
    const [couponPickerVisible, setCouponPickerVisible] = useState(false);
    const [orderOpen, setOrderOpen] = useState(orderStarting);
    const [currentSoc, setCurrentSoc] = useState('100%');
    const [currentCoupon, setCurrentCoupon] = useState({});
    const [chargeVoltage, setChargeVoltage] = useState(12); // 选择充电电压
    const [useIntegral, setUseIntegral] = useState(false); // 是否使用积分
    const [useCoupon, setUseCoupon] = useState(false); // 是否使用优惠券
    const [swiperCurrent, setSwiperCurrent] = useState(0); // 轮播
    const [discountOpen, setDiscountOpen] = useState(false);
    const [offlineOpen, setOfflineOpen] = useState(false);
    const [voltageOpen, setVoltageOpen] = useState(false);
    const [chargeVoltageTure, setChargeVoltageTure] = useState(12); // 选择充电电压(最终
    const { stationTel, tenantId } = currentPile;
    const integralForTenant = pointList.length ? pointList.find((i) => i.tenantId === tenantId)?.pointBalance : 0
    useDidShow(() => {
        wxLogin();
        const query = Taro.getStorageSync('useDidShowQuery') ? JSON.parse(Taro.getStorageSync('useDidShowQuery')) : {};
        console.log('QQQ', query);
        console.log('PPP', props);
        if (query && Object.keys(query).length && selectGunCode && currentPile.pileCode) {
            dispatch({
                type: 'stations/backToPile',
                payload: {
                    pileCode: currentPile.pileCode,
                    gunCode: selectGunCode,
                    needJump: false
                }
            });
        }
        dispatch({
            type: 'stations/upState',
            payload: {
                showStartModal: false,
                countDownTime: 90,
                errorMsg: ''
            }
        });
        dispatch({
            type: 'stations/findUserLoadingOrder'
        })
        dispatch({
            type: 'wallet/getBalance'
        })
        dispatch({
            type: 'stations/getChargingOrderInfo'
        })
        // getMyCoupons
        // dispatch({
        //     type: 'stations/getAllActivityByStation'
        // })
        setTimeout(() => {
            if (balance > 10) {
                setBalanceModalOpen(false);
            }
        })
        setOrderOpen(orderStarting);
        Taro.getNetworkType({
            success: function (res) {
                console.log('启动页面的网络连接', res);
                if(res?.networkType && res.networkType !== 'none'){
                    console.log('挖槽,启动页面有网', query);
                    Taro.onNetworkStatusChange((RES) => {
                        console.log('onNetworkStatusChange', RES);
                        if (RES.isConnected) {
                            //有网了以后，清空没网标识，进行页面刷新数据请求等...
                            console.log('启动页面有网了,网是', RES.networkType);
                            console.log('启动页面的PROPS', props);
                            if (selectGunCode && currentPile.pileCode) {
                                dispatch({
                                    type: 'stations/backToPile',
                                    payload: {
                                        pileCode: currentPile.pileCode,
                                        gunCode: selectGunCode,
                                        needJump: false
                                    }
                                });
                            };
                            // dispatch({
                            //     type: 'stations/findUserLoadingOrder'
                            // })
                            // dispatch({
                            //     type: 'wallet/getBalance'
                            // })
                            // dispatch({
                            //     type: 'stations/getChargingOrderInfo'
                            // })
                            // // getMyCoupons
                            // dispatch({
                            //     type: 'stations/getAllActivityByStation'
                            // })
                        } else {
                            //没网了，存个没网标识，然后需要请求的地方加个loading框
                            console.log('启动页面没网了');
                        }

                    })
                }
            }
        })
    })
    useEffect(() => {
        setOrderOpen(orderStarting);
        // setLoading(orderStarting)
    }, [orderStarting]);
    useEffect(() => {
        // setActivityVisible(!!allActivities.length && isScan);
        setActivityVisible(!!allActivities.length && isLogin && isScan);
    }, [allActivities.length, isLogin]);
    useEffect(() => {
        if ( currentPile.description){
            setDiscountOpen(true)
        };
        if (currentGun.gunStatus === '离线' || currentGun.gunStatus === '充电中'){
          setOfflineOpen(true)
        }
    }, [currentPile.stationId])
    const currentTimeRange = rateDetail && rateDetail.length ? rateDetail.find((i) => i.flag) : {};
    const timeStr = currentTimeRange?.timeStr ? currentTimeRange?.timeStr.replace('-', '~') : '';
    // console.log('currentPile', currentPile);
    // console.log('currentTimeRange', currentTimeRange);
    // console.log('timeStr', timeStr);
    const WrapperStyle = {
        display: 'flex',
        height: '100%',
        alignItems: 'center',
        justifyContent: 'center'
    }
    const socOptions = [
        [
            {value: 100, text: '100%'},
            {value: 99, text: '99%'},
            {value: 98, text: '98%'},
            {value: 97, text: '97%'},
            {value: 96, text: '96%'},
            {value: 95, text: '95%'},
            {value: 94, text: '94%'},
            {value: 93, text: '93%'},
            {value: 92, text: '92%'},
            {value: 91, text: '91%'},
            {value: 90, text: '90%'},
            {value: 89, text: '89%'},
            {value: 88, text: '88%'},
            {value: 87, text: '87%'},
            {value: 86, text: '86%'},
            {value: 85, text: '85%'},
            {value: 84, text: '84%'},
            {value: 83, text: '83%'},
            {value: 82, text: '82%'},
            {value: 81, text: '81%'},
            {value: 80, text: '80%'},
        ]
    ]
    const couponOptions = myCoupons.length ? myCoupons.map((i) => {
        return {
            value: i.couponId,
            // text: i.couponId,
            text: i.couponName,
        }
    }) : []

    function confirmSocPicker(opts, values) {
        setCurrentSoc(opts && opts.length ? opts[0].text : '')
    }

    function confirmCouponPicker(opts, values) {
        setCurrentCoupon(opts && opts.length ? opts[0] : '')
    }

    function makePhone(e) {

        e.stopPropagation();
        if (stationTel) {
            Taro.makePhoneCall({
                phoneNumber: stationTel.toString(),
            });
        } else {
            Taro.showToast({
                title: "暂未收录电站服务电话",
                icon: "none",
                duration: 1000,
            });
        }
    }

    // Taro.enableAlertBeforeUnload({
    //   message: "退出当前页面会导致启动失败?",
    //   success: function (res) {},
    //   fail: function (errMsg) {},
    // });
    const allCouponsAvailable = [];
    if (allActivities.length) {
        for (const d of allActivities) {
            if (d.coupons && d.coupons.length) {
                for (const l of d.coupons) {
                    allCouponsAvailable.push({
                        ...l,
                        activityId: d.activityId,
                        activityType: d.activityType,
                    })
                }
            }
        }
    }

    function colorFun(status) {
        switch (status) {
            case '空闲中':
                return '#42D361';
            case '已插枪':
                return '#FCC23A';
            case '充电中':
                return '#12BDF6';
            case '离线':
                return '#C2C0C0';
            default:
                return ''
        }
    }
    // useLaunch(() => {
    //     console.log('useLaunch')
    //
    // })
    return (
        <View className='stationDetailWrap'>
            {
                loading ?
                    <Overlay visible={loading}>
                        <div className='wrapper' style={WrapperStyle}>
                            <Loading direction='vertical'>加载中</Loading>
                        </div>
                    </Overlay> :
                    <View>
                        {
                            chargingOrderInfo && Object.keys(chargingOrderInfo).length ?
                                <ConfigProvider
                                    theme={{nutuiNoticebarBackground: '#fdcd5f', nutuiNoticebarColor: '#0091ff'}}
                                    style={{marginBottom: 12}}>
                                    <NoticeBar
                                        scrollable={false}
                                        content={
                                            <span>温馨提示:您已有正在充电的订单...
                              <span
                                  style={{
                                      color: '#0091FF',
                                      display: 'inline-block',
                                      textDecoration: 'underline',
                                      marginLeft: '12px'
                                  }}
                                  onClick={() => Taro.navigateTo({url: "/moduleA/pages/charging/index"})}
                              >
                              查看充电详情<AtIcon value='chevron-right' size='18' color='#0091FF'/>
                             </span>
                          </span>
                                        }
                                    />
                                </ConfigProvider> : null
                        }
                        <View className='stationInfo' style={{position: 'relative'}}>
                            <View style={{position: 'absolute', right: '0', top: '-9rpx'}}>
                                <Tag
                                    background={colorFun(currentGun.gunStatus)}
                                    color='#ffffff'
                                    round
                                >
                                    {currentGun.gunStatus}
                                </Tag>
                            </View>
                            <View className='cardContent'>
                                <View className='cardContentLeft'>
                                    <View className='line'>
                                        {currentGun.pileName}{String.fromCharCode(Number(gunIndex) + 64)}枪
                                    </View>
                                    <View className='line'>
                                        桩编号: {currentGun.pileCode}
                                        <AtIcon
                                            prefixClass='icon'
                                            value='copy' size='18'
                                            color='#0091FF'
                                            onClick={() => {
                                                Taro.setClipboardData({
                                                    //复制文本
                                                    data: currentGun.pileCode,
                                                    success: function () {
                                                        Taro.getClipboardData({
                                                            //获取复制文本
                                                            success: function () {
                                                                Taro.showToast({
                                                                    title: "充电桩编号已复制",
                                                                    icon: "none", //是否需要icon
                                                                    mask: "true", //是否设置点击蒙版，防止点击穿透
                                                                });
                                                            },
                                                        });
                                                    },
                                                });
                                            }}
                                        />
                                    </View>
                                </View>
                                <View>
                                    <View>
                                        <Text
                                            style={{color: '#237AF5'}}
                                            onClick={(e) => makePhone(e)}
                                        >
                                            <AtIcon value='phone' size={18}/>
                                            {stationTel}
                                        </Text>
                                    </View>
                                </View>
                            </View>
                            <View className='cardContent'>
                                <View className='cardContentSon'>
                                    <View className='target'>{currentGun.pileType}</View>
                                    <View>电桩类型</View>
                                </View>
                                <View className='cardContentSon'>
                                    <View className='target'>{currentGun.power}KW</View>
                                    <View>电桩功率</View>
                                </View>
                                <View className='cardContentSon'>
                                    <View className='target'>12/24V</View>
                                    <View>辅助电源</View>
                                </View>
                            </View>
                        </View>
                        <View className='stationInfo'>
                            {
                                currentPile.rebate ?
                                    <Badge value={`${currentPile.rebate / 10}折优惠`} style={{marginInlineEnd: '40px'}}>
                                        <div className='title'>
                                            充电费用
                                        </div>
                                    </Badge> : <div className='title'>充电费用</div>
                            }
                            <div className='position'>
                                <View className='address'>
                                    <Text>
                                        当前计费时段: {timeStr}
                                    </Text>
                                </View>
                                <View onClick={() => Taro.navigateTo({url: '/moduleA/pages/rate/index'})}>
                                    <Text>
                                        计费详情
                                    </Text>
                                    &nbsp;
                                    <AtIcon value='chevron-right' size='18' color='#767E8E'/>
                                </View>
                            </div>
                            <div className='type'>
                                <View style={{color: '#FA6400', fontWeight: 'bold'}}>
                                    {((currentTimeRange.chargePrice + currentTimeRange.servicePrice) *
                                        (currentPile.rebate ? (currentPile.rebate / 100) : 1)).toFixed(2)}
                                    <Text style={{fontSize: '24rpx'}}>元/度</Text>
                                </View>
                                {
                                    currentPile.rebate ?
                                        <View style={{
                                            color: '#767E8E',
                                            fontWeight: 'bold',
                                            fontSize: '24rpx',
                                            marginTop: '8rpx',
                                            marginLeft: '12rpx',
                                            textDecoration: 'line-through'
                                        }}
                                        >{(currentTimeRange.chargePrice + currentTimeRange.servicePrice).toFixed(2)} 元/度</View> : null
                                }
                            </div>
                        </View>
                        <View className='chargeInfoCard'>
                            <View>
                                <AtIcon prefixClass='icon' value='qianbao' size='18' color='#767E8E'/> 钱包余额
                                <Text style={{fontWeight: 'bold', color: '#ff6659'}}> {balance.toFixed(2)}元</Text>
                            </View>
                            <View onClick={() => Taro.navigateTo({url: '/moduleB/pages/wallet/recharge'})}>
                                去充值<AtIcon value='chevron-right' size='18' color='#767E8E'/>
                            </View>
                        </View>
                        {
                            integralForTenant ?
                                <View className='chargeInfoCard'>
                                    <View>
                                        <AtIcon prefixClass='icon' value='jifen' size='18' color='#767E8E'/> 当前积分
                                        <Text style={{fontWeight: 'bold', color: '#ff6659'}}> {(integralForTenant / 100).toFixed(2)}</Text>
                                    </View>
                                    <View style={{display: 'flex'}}>
                                        <Checkbox
                                            className='test'
                                            label='使用积分抵扣电费'
                                            labelPosition='left'
                                            defaultChecked={false}
                                            disabled={!integralForTenant}
                                            checked={useIntegral}
                                            onChange={(value) => {
                                                setUseIntegral(value);
                                                setUseCoupon(value ? false : useCoupon);
                                                setCurrentCoupon(value ? {} : currentCoupon)
                                            }}
                                        />
                                    </View>
                                </View> : null}
                        {
                            useCoupon && <View className='chargeInfoCard'>
                                <View><AtIcon prefixClass='icon' value='kaquan' size='18' color='#767E8E'/> 优惠券</View>
                                <View onClick={() => setCouponPickerVisible(true)}>
                                    {myCoupons.length ?
                                        <Tag
                                            type={!currentCoupon.value ? 'warning' : 'warning'}
                                            round
                                            style={{marginRight: '6rpx'}}
                                        >{currentCoupon.value ? '已选取' : '尚未选择优惠券'}
                                        </Tag>
                                        : null
                                    }
                                    <Text style={{fontWeight: 'bold', color: '#ff6659'}}>
                                        {
                                            currentCoupon.value ?
                                                currentCoupon.couponType === 1 ? `${currentCoupon.couponAmount || ''}元`
                                                    : `${currentCoupon.couponAmount || ''}折`
                                                : ''
                                        }
                                        {
                                            currentCoupon.value ? currentCoupon.couponObject === 1 ? '服务费券,' : '电费券,' : ''
                                        }
                                        {currentCoupon.value ?
                                            `${currentCoupon.conditionsAstrict ? currentCoupon.conditionsAstrict === 1 ? `电费满${currentCoupon.astrictAmount || ''}元可用` :
                                                `充电量满${currentCoupon.astrictAmount || ''}度可用` : '无使用门槛'}` : ''
                                        }
                                    </Text>
                                    <AtIcon value='chevron-right' size='18' color='#767E8E'/>
                                </View>
                            </View>
                        }
                        {
                            chargingOrderInfo && Object.keys(chargingOrderInfo).length ? null :
                                <View className='chargeInfoCard'>
                                    <View><AtIcon prefixClass='icon' value='chongdianzhong' size='18'
                                                  color='#767E8E'/> 充电安全控制</View>
                                    <View onClick={() => setSocPickerVisible(true)}>
                                        {currentSoc}<AtIcon value='chevron-right' size='18' color='#767E8E'/>
                                    </View>
                                </View>
                        }
                      {/*<View className='chargeInfoCard'>*/}
                      {/*  <View>*/}
                      {/*    <AtIcon prefixClass='icon' value='dianya' size='18' color='#767E8E'/> 充电电压*/}
                      {/*  </View>*/}
                      {/*  <View style={{display: 'flex'}}>*/}
                      {/*    <Checkbox*/}
                      {/*      className='test'*/}
                      {/*      label='12V'*/}
                      {/*      labelPosition='left'*/}
                      {/*      defaultChecked={false}*/}
                      {/*      checked={chargeVoltage === 12}*/}
                      {/*      onChange={(value) => {*/}
                      {/*          setChargeVoltage(12)*/}
                      {/*      }}*/}
                      {/*    />*/}
                      {/*      &nbsp;*/}
                      {/*      <Checkbox*/}
                      {/*          className='test'*/}
                      {/*          label={<Text style={{fontWeight: 'bold', color: 'red'}}>24V</Text>}*/}
                      {/*          labelPosition='left'*/}
                      {/*          defaultChecked={false}*/}
                      {/*          checked={chargeVoltage === 24}*/}
                      {/*          onChange={(value) => {*/}
                      {/*              setChargeVoltage(24);*/}
                      {/*              setVoltageOpen(true);*/}
                      {/*          }}*/}
                      {/*      />*/}
                      {/*  </View>*/}
                      {/*</View>*/}
                    </View>
            }
            <View className='pageFooter'>
                <View className='priceInFooter'>
                    <View style={{color: '#FA6400', fontWeight: 'bold'}}>
                        计费:
                        {currentPile.rebate ? ((currentTimeRange.chargePrice + currentTimeRange.servicePrice) * (currentPile.rebate / 100)).toFixed(2) :
                            (currentTimeRange.chargePrice + currentTimeRange.servicePrice).toFixed(2)}
                        <Text style={{fontSize: '24rpx'}}>元/度</Text>
                    </View>
                </View>
                <View className='buttonInFooter'>
                    <AtButton
                      //   disabled={
                      // Object.keys(chargingOrderInfo).length || orderStarting || startLoading ||
                      //       currentGun.gunStatus === '离线' || currentGun.gunStatus === '充电中'}
                        // loading={startLoading}
                        onClick={() => {
                            if (action) {
                                dispatch({
                                    type: 'stations/upState',
                                    payload: {
                                        action
                                    }
                                });
                            }
                            if (useIntegral) {
                                setTimeout(() => {
                                    dispatch({
                                        type: 'stations/createOrder',
                                        payload: {
                                            gunNum: gunIndex,
                                            orderSource: 1,
                                            pileCode: currentGun.pileCode,
                                            soc: parseInt(currentSoc.slice(0, currentSoc.length - 1)),
                                            payType: 2,
                                            separateAccount: 1,
                                            pileType: currentGun.pileType,
                                            bmsVoltage: chargeVoltageTure
                                        }
                                    })
                                }, 100)
                            } else if (myCoupons.length) {
                                setUseCoupon(!useIntegral);
                                setCurrentCoupon({});
                                setCouponPickerVisible(!useIntegral);
                            } else {
                                setTimeout(() => {
                                    dispatch({
                                        type: 'stations/createOrder',
                                        payload: {
                                            gunNum: gunIndex,
                                            orderSource: 1,
                                            pileCode: currentGun.pileCode,
                                            soc: parseInt(currentSoc.slice(0, currentSoc.length - 1)),
                                            payType: 1,
                                            separateAccount: 1,
                                            pileType: currentGun.pileType,
                                            bmsVoltage: chargeVoltageTure
                                        }
                                    })
                                }, 100)
                            }
                        }}
                    >{startLoading ? '启动中...' : '立即充电'}</AtButton>
                </View>
            </View>
            <ConfigProvider theme={{nutuiPickerOkColor: '#0091FF'}}>
                <Picker
                    visible={socPickerVisible}
                    options={socOptions}
                    duration={1000}
                    onConfirm={(list, values) => confirmSocPicker(list, values)}
                    onClose={() => setSocPickerVisible(false)}
                />
            </ConfigProvider>
            <AtActionSheet
                title='选择优惠券'
                isOpened={couponPickerVisible}
                onClose={() => {
                    setCurrentCoupon({});
                    setUseCoupon(false);
                    setCouponPickerVisible(false);
                }}
                onCancel={() => {
                    setTimeout(() => {
                        dispatch({
                            type: 'stations/createOrder',
                            payload: {
                                gunNum: gunIndex,
                                orderSource: 1,
                                pileCode: currentGun.pileCode,
                                soc: parseInt(currentSoc.slice(0, currentSoc.length - 1)),
                                couponName: currentCoupon?.text,
                                couponId: currentCoupon?.value,
                                payType: 1,
                                separateAccount: 1,
                                pileType: currentGun.pileType,
                                bmsVoltage: chargeVoltageTure
                            }
                        })
                        // console.log('parseFloat(balance)', parseFloat(balance)); // 低于十元仍可选择启动功能,暂时屏蔽,代码勿删
                        // if (0 < parseFloat(balance) && parseFloat(balance) <= 10){
                        //     setBalanceModalOpen(true)
                        // } else {
                        //     dispatch({
                        //         type: 'stations/createOrder',
                        //         // type: 'stations/startGun',
                        //         payload: {
                        //             gunNum: gunIndex,
                        //             orderSource: 1,
                        //             pileCode: currentGun.pileCode,
                        //             soc: parseInt(currentSoc.slice(0, currentSoc.length - 1))
                        //         }
                        //     })
                        // }
                    }, 500);
                    setCouponPickerVisible(false)
                }}
                cancelText={
                    currentCoupon && currentCoupon.couponId ?
                        <div className='couponBtn'>选好了,开始充电</div> :
                        <div className='couponBtnNo'>不用优惠,直接充电</div>}
            >
                {
                    myCoupons && myCoupons.length ? [...myCoupons].map((i) => (
                        <AtActionSheetItem
                            className='couponWrap'
                            onClick={() => {
                                if (currentCoupon.couponId && i.couponId === currentCoupon.couponId) {
                                    setCurrentCoupon({});
                                } else {
                                    setCurrentCoupon({
                                        text: i.couponName,
                                        value: i.couponId,
                                        ...i
                                    });
                                }
                                // setCouponPickerVisible(false)
                            }}
                        >
                            <View className='couponItem' style={{width: '90%'}}>
                                <div className='couponLeftTag'>{i.couponObject === 1 ? '服务费' : '电费'}</div>
                                <div className='couponCardItemOld'>
                                    <div className='couponLeft'>
                                        {i.couponId === currentCoupon.couponId ?
                                            <Checkbox checked style={{marginRight: '14rpx'}}/> :
                                            <Checkbox checked={false} style={{marginRight: '14rpx'}}/>}
                                        {
                                            i.couponType === 1 ? <div style={{whiteSpace: 'nowrap'}}><span
                                                    className='value'>¥{i.couponAmount || ''}</span></div>
                                                : <div style={{whiteSpace: 'nowrap'}}><span
                                                    className='value'>{i.couponAmount || ''}折</span></div>
                                        }
                                    </div>
                                    <div className='couponLine'/>
                                    <div className='couponCenter'>
                                        <div
                                            className='name'>{`${i.conditionsAstrict ? i.conditionsAstrict === 1 ? `电费满${i.astrictAmount || ''}元可用` : `充电量满${i.astrictAmount || ''}度可用` : '无使用门槛'}`}</div>
                                    </div>
                                </div>
                            </View>
                        </AtActionSheetItem>
                    )) : null
                }
            </AtActionSheet>
            {/*<ConfigProvider theme={{nutuiPickerOkColor: '#0091FF'}}>*/}
            {/*    <Picker*/}
            {/*        visible={couponPickerVisible}*/}
            {/*        options={[*/}
            {/*            // {value: 0, text: '不使用优惠券'},*/}
            {/*            ...couponOptions*/}
            {/*        ]}*/}
            {/*        duration={1000}*/}
            {/*        onConfirm={(list, values) => confirmCouponPicker(list, values)}*/}
            {/*        onClose={() => setCouponPickerVisible(false)}*/}
            {/*    />*/}
            {/*</ConfigProvider>*/}
            <Dialog
                visible={showStartModal}
                title={errorMsg && <View style={{fontSize: '32rpx', fontWeight: 'bolder'}}>启动失败</View>}
                footer={!errorMsg && null}
                confirmText={errorMsg === '余额不足10元,请先充值' ? '立即充值' : '重新启动'}
                closeOnOverlayClick={false}
                onConfirm={() => {
                    // clearInterval(timer);
                    dispatch({
                        type: 'stations/upState',
                        payload: {
                            countDownTime: 90
                        }
                    })
                    // timer = setInterval(() => dispatch({type: 'stations/upState', payload: {countDownTime: countDownTime - 1}}), 1000)
                    if (errorMsg === '余额不足10元,请先充值'){
                        Taro.navigateTo({url: '/moduleB/pages/wallet/recharge'})
                    } else {
                        if (useIntegral) {
                            setTimeout(() => {
                                dispatch({
                                    type: 'stations/createOrder',
                                    payload: {
                                        gunNum: gunIndex,
                                        orderSource: 1,
                                        pileCode: currentGun.pileCode,
                                        soc: parseInt(currentSoc.slice(0, currentSoc.length - 1)),
                                        payType: 2,
                                        separateAccount: 1,
                                        pileType: currentGun.pileType,
                                        bmsVoltage: chargeVoltageTure
                                    }
                                })
                            }, 500)
                        } else {
                            const payloadData = {
                                gunNum: gunIndex,
                                orderSource: 1,
                                pileCode: currentGun.pileCode,
                                soc: parseInt(currentSoc.slice(0, currentSoc.length - 1)),
                                payType: 1,
                                separateAccount: 1,
                                pileType: currentGun.pileType,
                                bmsVoltage: chargeVoltageTure
                            };
                            if (currentCoupon && currentCoupon?.value) {
                                payloadData.couponName = currentCoupon?.text;
                                payloadData.couponId = currentCoupon?.value
                            }
                            setTimeout(() => {
                                dispatch({
                                    type: 'stations/createOrder',
                                    payload: {
                                        ...payloadData
                                    }
                                })
                            }, 500)
                        }
                    }
                }}
                onCancel={() => {
                    dispatch({
                        type: 'stations/upState',
                        payload: {
                            showStartModal: false,
                            errorMsg: '',
                           countDownTime: 90
                        }
                    });
                    Taro.reLaunch({
                        url: '/pages/index/index'
                    });
                }}
            >
                {
                    errorMsg ? <View style={{
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            textAlign: 'center',
                            fontSize: '36rpx',
                            fontWeight: 'bold',
                            lineHeight: '50rpx',
                            color: '#FA6400',
                            flexWrap: 'wrap',
                            fontFamily: '楷体'
                        }}>{errorMsg}</View> :
                        <View style={{textAlign: 'center'}}>
                            <ConfigProvider
                                theme={{
                                    nutuiLoadingIconColor: '#396aca',
                                    nutuiLoadingIconSize: '66px',
                                    nutuiLoadingTextSize: '16px'
                                }}
                            >
                                <Loading direction='vertical' type='spinner'>提示</Loading>
                            </ConfigProvider>
                            <View
                                style={{
                                    display: 'flex',
                                    justifyContent: 'center',
                                    fontSize: '28rpx',
                                    fontWeight: 'bold',
                                    flexWrap: 'wrap'
                                }}
                            >
                                <View>正在启动充电,可能需要</View>
                                <Text style={{
                                    color: '#396aca',
                                    fontSize: '36rpx',
                                    fontWeight: 'bold'
                                }}> {countDownTime} </Text>
                                <View>秒时间,请耐心等待。</View>
                            </View>
                        </View>
                }
            </Dialog>
            <Dialog
                title={<View style={{fontSize: '32rpx', fontWeight: 'bolder'}}>余额不足提示</View>}
                visible={balanceModal}
                confirmText='立即充值'
                cancelText={parseFloat(balance) <= 0 ? '取消' : '仍要启动'}
                closeOnOverlayClick={false}
                onConfirm={() => Taro.navigateTo({url: '/moduleB/pages/wallet/recharge'})}
                onCancel={() => {
                    if (parseFloat(balance) <= 0) {
                        setBalanceModalOpen(false)
                    } else {
                        // dispatch({
                        //     type: 'stations/createOrder',
                        //     payload: {
                        //         gunNum: gunIndex,
                        //         orderSource: 1,
                        //         pileCode: currentGun.pileCode,
                        //         soc: parseInt(currentSoc.slice(0, currentSoc.length - 1))
                        //     }
                        // });
                        if (useIntegral) {
                            setTimeout(() => {
                                dispatch({
                                    type: 'stations/createOrder',
                                    payload: {
                                        gunNum: gunIndex,
                                        orderSource: 1,
                                        pileCode: currentGun.pileCode,
                                        soc: parseInt(currentSoc.slice(0, currentSoc.length - 1)),
                                        payType: 2,
                                        separateAccount: 1,
                                        pileType: currentGun.pileType,
                                        bmsVoltage: chargeVoltageTure
                                    }
                                })
                            }, 500)
                        } else {
                            const payloadData = {
                                gunNum: gunIndex,
                                orderSource: 1,
                                pileCode: currentGun.pileCode,
                                soc: parseInt(currentSoc.slice(0, currentSoc.length - 1)),
                                payType: 1,
                                separateAccount: 1,
                                pileType: currentGun.pileType,
                                bmsVoltage: chargeVoltageTure
                            };
                            if (currentCoupon && currentCoupon?.value) {
                                payloadData.couponName = currentCoupon?.text;
                                payloadData.couponId = currentCoupon?.value
                            }
                            setTimeout(() => {
                                dispatch({
                                    type: 'stations/createOrder',
                                    payload: {
                                        ...payloadData
                                    }
                                })
                            }, 500)
                        }
                        setBalanceModalOpen(false)
                    }
                }}
            >
                <View
                    style={{
                        display: 'flex',
                        justifyContent: 'center',
                        fontSize: '28rpx',
                        fontWeight: 'bold',
                        flexWrap: 'wrap'
                    }}
                >
                    <View>{parseFloat(balance) <= 0 ? '当前余额为: 0,无法启动充电' : `您的钱包余额为: ${balance},建议提前充值,确保充电顺畅`}</View>
                </View>
            </Dialog>
            <AtModal isOpened={isOpened} closeOnClickOverlay={false}>
                <AtModalHeader>温馨提示</AtModalHeader>
                <AtModalContent>
                    <View className='modalContent'>
                        请先登录再进行操作
                    </View>
                </AtModalContent>
                <AtModalAction>
                    <View className='modalFooter'>
                        <AtButton
                            plain
                            style={{border: 'none'}}
                            onClick={() => {
                                Taro.reLaunch({
                                    url: '/pages/index/index'
                                });
                                setOpen(false)
                            }}
                        >取消</AtButton>
                        <AtButton
                            plain
                            style={{border: 'none'}}
                            openType='getPhoneNumber'
                            onGetPhoneNumber={(e) => {
                                const accessToken = Taro.getStorageSync('access_token')
                                const {detail: {iv, encryptedData} = {}} = e;
                                if (encryptedData && iv) {
                                    // wxLogin();
                                    setTimeout(() => {
                                        const session_key = Taro.getStorageSync('session_key') || '';
                                        const openid = Taro.getStorageSync('openid') || '';
                                        if (openid && session_key) {
                                            Taro.request({
                                                url: `${base}/mini/wxLogin`,
                                                data: {
                                                    encryptedData,
                                                    iv,
                                                    openid,
                                                    sessionKey: session_key
                                                },
                                                header: {
                                                    "content-type": "application/json",
                                                    "appid": 'wx52f6aba688ce70f6',
                                                    "Authorization": accessToken ? "Bearer " + accessToken : '',
                                                },
                                                method: "POST",
                                            }).then((res) => {
                                                const {data: {code, data: {phoneNumber: phone, token} = {}} = {}} = res;
                                                if (code === 200) {
                                                    Taro.showToast({
                                                        title: '登录成功',
                                                        icon: 'success'
                                                        // duration: 2000
                                                    })
                                                    Taro.setStorageSync('isLogin', true);
                                                    Taro.setStorageSync('access_token', token);
                                                    Taro.setStorageSync('phoneNumber', phone);
                                                    dispatch({
                                                        type: 'wallet/getBalance'
                                                    })
                                                    dispatch({
                                                        type: 'stations/getChargingOrderInfo'
                                                    })
                                                    // dispatch({
                                                    //     type: 'stations/attendActivity'
                                                    // })
                                                    dispatch({
                                                        type: 'stations/getMyCoupons'
                                                    });
                                                    dispatch({
                                                        type: 'stations/getMyCouponsByStation'
                                                    })
                                                    setOpen(false)
                                                } else {
                                                    Taro.showToast({
                                                        title: '登录失败,请重试',
                                                        icon: 'none'
                                                    })
                                                }
                                            });
                                        }
                                    }, 500)
                                }
                            }}
                        >确定</AtButton>
                    </View>
                </AtModalAction>
            </AtModal>
            <AtModal
                isOpened={discountOpen}
                closeOnClickOverlay={false}
            >
                <AtModalHeader>温情提示</AtModalHeader>
                <AtModalContent>
                    <View className='modalContentDis'>
                        <RichText nodes={currentPile.description}/>
                    </View>
                </AtModalContent>
                <AtModalAction>
                    <View className='modalFooterDis'>
                        <AtButton
                            plain
                            onClick={() => {
                                setDiscountOpen(false)
                            }}
                        >知道了</AtButton>
                    </View>
                </AtModalAction>
            </AtModal>
            <AtModal
                isOpened={offlineOpen}
                closeOnClickOverlay={false}
            >
                <AtModalHeader>服务提醒</AtModalHeader>
                <AtModalContent>
                    <View className='modalContentDis'>
                        该充电枪状态为: <Text style={{color: colorFun(currentGun.gunStatus)}}>{currentGun.gunStatus}</Text>, 暂无法提供充电服务.
                    </View>
                </AtModalContent>
                <AtModalAction>
                    <View className='modalFooterDis'>
                        <AtButton
                            plain
                            onClick={() => {
                                setOfflineOpen(false)
                            }}
                        >知道了</AtButton>
                    </View>
                </AtModalAction>
            </AtModal>
            <AtModal
                isOpened={activityVisible}
                footer={null}
                closeOnClickOverlay={false}
                // closeIcon
                // closeIconPosition='bottom'
                onClose={() => setActivityVisible(false)}
                className='activeWrap'
            >
                <AtModalHeader>
                    <View className='top-images'>
                        <Image src='https://jgdq.obs.cn-southwest-2.myhuaweicloud.com/jgy/images/20241203082256.gif' mode='widthFix'
                               width='172px'></Image>
                    </View>
                </AtModalHeader>
                <AtModalContent className='couponWrap'>
                    <ScrollView style={{maxHeight: '500rpx', minHeight: '280rpx'}} scrollY>
                        {
                            allCouponsAvailable.length ? [...allCouponsAvailable].map((i) => (
                                <View className='couponItem'>
                                    <div className='couponLeftTag'>{i.couponObject === 1 ? '服务费' : '电费'}</div>
                                    <div className='couponCardItem'>
                                        <div className='couponLeft'>
                                            {
                                                i.couponType === 1 ? <div style={{whiteSpace: 'nowrap'}}><span
                                                        className='value'>¥{i.couponAmount || ''}</span></div>
                                                    : <div style={{whiteSpace: 'nowrap'}}><span
                                                        className='value'>{i.couponAmount || ''}折</span></div>
                                            }
                                            <div className='desc'>
                                                {`${i.conditionsAstrict ? i.conditionsAstrict === 1 ? `电费满${i.astrictAmount || ''}元可用` : `充电量满${i.astrictAmount || ''}度可用` : '无门槛'}`}
                                            </div>
                                        </div>
                                        <div className='couponLine'/>
                                        <div className='couponCenter'>
                                            <div className='name'>{i.couponName}</div>
                                            <div
                                                className='validityTime'>{i.couponValidityType === 1 ? `${i.validityTime || ''}到期` : `领取后${i.validityTime || ''}天内可用`}</div>
                                        </div>
                                        {
                                            i.drawDown === 1 ?
                                                <div className='rightTag' style={{backgroundColor: 'transparent'}}><Tag
                                                    type='warning'>已领取</Tag></div> : <div
                                                    className='right'
                                                    onClick={() => {
                                                        dispatch({
                                                            type: 'stations/attendActivity',
                                                            payload: {
                                                                activityId: i.activityId,
                                                                activityType: i.activityType,
                                                                couponId: i.couponId,
                                                            }
                                                        })
                                                    }}
                                                >领取</div>
                                        }
                                    </div>
                                </View>
                            )) : null
                        }
                    </ScrollView>
                </AtModalContent>
                <AtModalAction>
                    <View className='couponFooter' onClick={() => setActivityVisible(false)}>关闭</View>
                </AtModalAction>
            </AtModal>
            <AtModal
                isOpened={voltageOpen}
                closeOnClickOverlay={false}
            >
                <AtModalHeader>
                    <Text style={{fontWeight: 'bold', color: '#ff7414'}}>
                        <AtIcon prefixClass='icon' value='guzhang' size='18' color='#ff7414'/>电压确认！！！
                    </Text>
                </AtModalHeader>
                <AtModalContent>
                    <View className='modalContentDis'>
                        <Text style={{fontWeight: 'bold', }}>注意:  </Text>
                        <Text style={{fontWeight: 'bold', color: 'red'}}>24V</Text>充电电压仅适用于
                        <Text style={{fontWeight: 'bold', color: 'red'}}>某些重型卡车</Text>运输车辆;
                        <View>
                            请务必:
                            <Text style={{fontWeight: 'bold', color: 'red'}}>谨慎确认您的爱车是否能承受24V的充电电压;</Text>
                        </View>
                    </View>
                </AtModalContent>
                <AtModalAction>
                    <View className='modalFooterVoltage'>
                        <AtButton
                            plain
                            onClick={() => {
                                setVoltageOpen(false);
                                setChargeVoltageTure(12)
                                setChargeVoltage(12)
                            }}
                        >取消选择</AtButton>
                        <Divider direction="vertical" style={{height: '100%'}} />
                        <AtButton
                            plain
                            onClick={() => {
                                setVoltageOpen(false)
                                setChargeVoltageTure(24)
                                setChargeVoltage(24)
                            }}
                        ><Text style={{color: 'red'}}>确认24V</Text></AtButton>
                    </View>
                </AtModalAction>
            </AtModal>
        </View>
    )
}

function mapStateToProps({
                             stations: {
                                 chargingOrderInfo = {},
                                 currentPile = {},
                                 currentGun = {},
                                 allActivities = [],
                                 myCouponsByStation = [],
                                 rateDetail = [],
                                 selectGunCode = '',
                                 countDownTime,
                                 showStartModal = false,
                                 orderStarting = false,
                                 errorMsg = ''
                             } = {},
                             wallet: {
                                 balance,
                                 integral,
                                 pointList = []
                             } = {},
                             loading: {
                                 effects: {
                                     "stations/initDetail": loading = false,
                                     "stations/createOrder": startLoading = false,
                                 } = {}
                             } = {},
                         }) {
    return {
        chargingOrderInfo,
        currentPile,
        currentGun,
        allActivities,
        myCouponsByStation,
        rateDetail,
        selectGunCode,
        countDownTime,
        showStartModal,
        orderStarting,
        errorMsg,
        balance,
        integral,
        pointList,
        startLoading,
        loading,
    };
}

export default connect(mapStateToProps)(Index);
